<template>
  <div class="layer-tools">
    <!-- <img
      v-popover:popover
      :src="img_active === 2 ? imgObj.active : imgObj.img"
      :title="imgObj.title"
      @click="handleImgs"
    /> -->

    <ul class="layer-select-box" :style="{ height: height }">
      <li
        v-for="item in layerSelectlist"
        :key="item"
        :class="{ 'layer-select-li': true, active: layerActive === item }"
        @click="handleLayer(item)"
      >
        {{ item }}
      </li>
    </ul>

    <multiple-road-popups ref="multipleRoadRef" @setting-out="settingRoad" />
  </div>
</template>
<script>
  import { defineComponent, reactive, toRefs, onMounted, computed, nextTick, ref } from 'vue';
  import { useRoadInfoMarker } from './useRoadInfoMarker';
  import { useMapStore } from '@/store/modules/map';
  import { addmarker, maketList } from '@/layout/tabs/maps/setPoint.js';
  import { draw, clearDraw, drawClose } from '@/layout/tabs/maps/DrawingManage.js';
  import { HeatmapLayer, clearLayer } from '@/layout/tabs/maps/heatmapLayer';
  import { lineLayers, removeLine } from '@/layout/tabs/maps/lines';
  import { polyline } from '@/layout/tabs/maps/polyline';
  import multipleRoadPopups from '@/components/multipleRoadPopups/index';
  import { polylineColor } from '@/utils/polyLineColor';

  export default defineComponent({
    name: 'LayerTools',
    components: { multipleRoadPopups },
    props: {
      defaultViews: {
        type: String,
        default: '拥堵情况',
      },
    },
    emits: ['box-selection'],
    setup(props, { emit }) {
      const mapStore = useMapStore();

      const state = reactive({
        multipleRoadRef: null,
        map: computed(() => mapStore.ownMap),
        layerActive: props.defaultViews,
        height: 0,
        layerSelectlist: ['拥堵情况', '道路基础', '公共设施'],
        img_active: -1,
        marker4: null,
        isTool: false,
        drawingManager: null,
        geoc: null,
        markerList: [],
        polylineColor,
      });

      const { removeRoadInfoMarker } = useRoadInfoMarker({
        isTool: () => state.isTool,
        viewName: () => state.layerActive,
      });

      const handleImgs = () => {
        state.multipleRoadRef.isRoad = false;
        state.img_active = state.img_active == 2 ? -1 : 2;
        if (state.img_active == -1) {
          changeTool(1);
          return;
        }
        // if (state.img_active === index && state.height != 0) {
        //   console.log(1);
        //   state.img_active = -1;
        //   state.height = 0;
        // mapStore.setMarqueeTool(-1)
        //   return;
        // }
        // state.height = index === 1 ? '138px' : 0;
        // state.img_active = index;
        changeTool(state.img_active);
        // mapStore.setMarqueeTool(index)
      };

      // 选择 图层事件
      const handleLayer = (name) => {
        state.layerActive = name;
        addMapData(name);
        // mapStore.setLayerView(name);
        state.height = 0;
      };

      const clearMapObj = () => {
        state.map.clearOverlays();
        // 清除 图标 maker
        for (let i = 0; i < state.markerList.length; i++) {
          state.map.removeOverlay(state.markerList[i]);
        }
        state.markerList = [];
        removeRoadInfoMarker();
      };

      /**
       * 向地图添加数据
       * @param {*} val 页面名称
       */
      const addMapData = (val) => {
        clearDraw();
        switch (val) {
          case 'home':
            clearLayer();
            // 道路线条 + 地图点击事件
            // lineLayers(state.map);
            state.isTool = false;
            state.map.centerAndZoom(new window.BMap.Point(118.299146, 35.123191), 15);
            break;
          // ! 目前未使用此分支
          case '拥堵情况':
            // 隐藏道路基础信息弹窗
            mapStore.setShowPop('');
            // 热力图 + 道路线条
            clearMapObj();
            // HeatmapLayer(state.map);
            // lineLayers(state.map);
            break;
          case '道路基础':
            // 清除 线条
            removeLine(state.map);
            // 清除热力图
            clearLayer();
            clearMapObj();
            break;
          // ! 此分支目前未使用
          case '公共设施':
            mapStore.setShowPop('');
            // 清除 线条
            removeLine(state.map);
            // 清除热力图
            clearLayer();
            // 标记点
            makerList(state.map);
            break;
        }
      };

      // 图层工具 / 框选工具
      const changeTool = (val) => {
        switch (val) {
          case 1:
            // 工具
            state.isTool = false;
            // clearMapObj()
            state.drawingManager?.close();
            clearMapObj();
            break;
          // 划线工具
          case 2:
            state.isTool = true;
            // state.layerActive = '';
            mapStore.setShowPop(''); // 隐藏道路基础信息弹窗
            clearMapObj();
            state.map.clearOverlays();
            // 清除地图点击事件
            state.map.removeEventListener('click');
            setTimeout(() => {
              state.drawingManager = draw(state.map, (e) => {
                console.log(e.overlay);
                console.log('e :>> ', e);
                const list = e.overlay.Ho;
                // mapStore.setMarqueeTool(-1)
                mapStore.mapChangeOk(true);
                const locationList = [];
                list.map(async (i) => {
                  await geocLocation(i, (data) => {
                    locationList.push(data);
                  });
                });
                setTimeout(() => {
                  state.isTool = false;
                  state.multipleRoadRef.fetchData(locationList);
                  emit('box-selection', locationList);
                }, 500);
              });
            }, 100);
            break;
          case 0:
            state.isTool = false;
            clearMapObj();
            state.map.removeEventListener('click');
            state.drawingManager?.close();
            break;
        }
      };

      // 添加maker
      const makerList = (map) => {
        const list = maketList;
        list.map((i) => {
          const marker = addmarker(map, i);
          state.markerList.push(marker);
          map.addOverlay(marker);
          // marker.addEventListener("click", (e) => {
          //   var p = e
          //   console.log(p)
          // })
        });
      };

      const geocLocation = (point, callback) => {
        // 道路信息
        state.geoc.getLocation(point, function (rs) {
          const { addressComponents } = rs;
          if (callback) {
            callback(addressComponents);
          }
        });
      };

      // 根据点击道路 信息 画线
      const settingRoad = (row) => {
        const ghdldj = row.ghdldj;
        const lineColor = state.polylineColor.find((i) => i.type == ghdldj);
        const arr = row.coordinate.split(',');
        mapStore.setShowPolyline(true);
        polyline(state.map, arr, lineColor?.color);
      };

      onMounted(() => {
        // 默认隐藏道路规划等级弹窗
        mapStore.setShowPolyline(false);

        nextTick(() => {
          state.geoc = new window.BMap.Geocoder();
          addMapData(state.layerActive);
        });
      });

      // setTimeout(() => {
      //   state.map.addControl(
      //     new BMap.MapTypeControl({
      //       mapTypes: ['BMAP_NORMAL_MAP'],
      //       type: BMAP_MAPTYPE_CONTROL_MAP,
      //     }),
      //   );
      // }, 100);

      return {
        ...toRefs(state),
        handleLayer,
        handleImgs,
        addMapData,
        settingRoad,

        /**
         * 按钮图片
         */
        imgObj: {
          img: require('../../assets/images/maps/marquee_tool.png'),
          active: require('../../assets/images/maps/marquee_tool_active.png'),
          title: '框选工具',
        },
      };
    },
  });
</script>
<style lang="less" scoped>
  .layer-tools {
    margin-left: auto;
    display: flex;
    position: relative;

    img {
      margin-left: 20px;
      cursor: pointer;
    }

    .layer-select-box {
      overflow: hidden;
      position: absolute;
      left: -67%;
      top: 111%;
      width: 160px;
      z-index: 99;
      color: white;
      transition: height 0.5s;
      background-color: #000;
      // background-color: rgba(0, 0, 0, 0.2);
      // border-radius: 6px;
      // border: 1px solid rgba(255, 255, 255, 0.1);
      // padding: 10px;
      .layer-select-li {
        cursor: pointer;
        color: #b4b5b7;
        font-size: 16px;
        height: 40px;
        line-height: 40px;
        position: relative;
        padding: 0 12px;
        margin-bottom: 7px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        background-color: rgba(255, 255, 255, 0.1);

        &::after {
          position: absolute;
          content: '';
          width: 3px;
          height: 25px;
          left: 0;
          top: 21%;
          background-color: #4d5059;
        }

        &:hover {
          opacity: 0.8;
        }
      }

      .active {
        background: url(../../assets/images/maps/active.png) no-repeat;
        background-size: 100% 100%;
        color: #fff;

        &:after {
          display: none;
        }
      }
    }
  }
</style>
